package com.yupi.springbootinit.manager;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.service.UserService;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

@Service
public class WenxinManager {

    @Resource
    private UserService userService;

    @Value("${gear.wenxin.model-url}")
    private String modelUrl;

    @Value("${gear.wenxin.api-key}")
    private String apiKey;

    @Value("${gear.wenxin.secret-key}")
    private String secretKey;

    // 用yi_34b_chat模型会话
    public String doChatByWenxin(String massage, Long userId) throws IOException {
        // 先从数据库获取文心token数据，如果数据库没有再请求一个新的文心一言token存入数据库中
        User user = userService.getById(userId);
        String accessToken = user.getWenxinToken();
        if (accessToken.isEmpty()){
            accessToken = getAccessToken(userId);
        }
        String myPrompt = "现在我先给你prompt，我希望你会严格按照我为你设定的prompt回答，你是一个数据分析师和前端开发专家，接下来我会按照以下固定格式给你提供内容：\n" +
                "分析需求：\n" +
                "{数据分析的需求或者目标}\n" +
                "原始数据：\n" +
                "{csv格式的原始数据，用,作为分隔符}\n" +
                "请根据这两部分内容，按照以下指定格式生成内容（内容以“#######”分隔为两部分，此外不要输出任何多余的开头、结尾、注释）\n" +
                "#######\n" +
                "{前端Echarts V5的option配置对象的json代码，合理地将数据进行可视化，不要生成任何多余的内容，比如注释}\n" +
                "#######\n" +
                "{明确的数据分析结论、越详细越好，不要生成多余的注释}\n" +
                "以上就是我为你设定的prompt，我为你提供的内容如下：\n";

        HashMap<String, String> msg = new HashMap<>();
        msg.put("role", "user");
        msg.put("content", myPrompt+massage);

        ArrayList<HashMap> messages = new ArrayList<>();
        messages.add(msg);

        HashMap<String, Object> requestBody = new HashMap<>();
        requestBody.put("messages", messages);
        System.out.println("给ai发送消息："+requestBody);

        String response = HttpUtil.post(modelUrl + "?access_token=" + accessToken, JSONUtil.toJsonStr(requestBody));

        System.out.println("接收ai的返回信息："+response);
        // 提取返回数据中的“result”数据
        String extractData = extractData(response, userId);
        return extractData;
        // {"id":"as-agirnym2vb","object":"chat.completion","created":1704968093,"result":"你好！我是零一万物开发的一个智能助手，我叫 Yi，我是由零一万物的研究团队通过大量的文本数据进行训练，学习了语言的各种模式和关联，从而能够   满足你的需求。","is_truncated":false,"need_clear_history":false,"usage":{"prompt_tokens":3,"completion_tokens":41,"total_tokens":44}}
    }

    // 提取返回数据中的“result”数据
    private String extractData(String response, Long userId) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response);

            // 如果返回体中的"result"信息不为空
            if (jsonNode.hasNonNull("result")){
                String result = jsonNode.get("result").asText();
                System.out.println(result);
                return result;
            }
            if (jsonNode.hasNonNull("error_code")){
                int token = jsonNode.get("error_code").asInt();
                if (token == 110 || token == 100 || token == 111){
                    getAccessToken(userId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    // 获取accessToken，并将新获取的token信息存入数据库中
    public String getAccessToken(Long userId) throws IOException {

        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&"+apiKey+"&"+secretKey;
        // client_id=ow3heQ59CQPKfECqyz3MnUFE
        // client_secret=kyIYETAmCMH3uPS9bfI5Lm1PAPVGru2g

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        httpPost.setHeader("Content-type", "application/json");
        httpPost.addHeader("Accept", "application/json");

        // 执行请求并获取响应
        HttpResponse response = httpClient.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity());
        System.out.println("返回3"+result);
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(result);

            // 如果返回体中的"access_token"信息不为空
            if (jsonNode.hasNonNull("access_token")){
                String token = jsonNode.get("access_token").asText();
                System.out.println(result);

                // 将新获取的token信息存入数据库中
                User userToken = new User();
                userToken.setId(userId);
                userToken.setWenxinToken(token);
                userService.updateById(userToken);
                return token;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
        // {"refresh_token":"25.9bd22e3ba07aaf004ca6336926575369.315360000.2020359733.282335-46678315","expires_in":2592000,"session_key":"9mzdXUddT5sqYx61B93T1x+zUMFvVD21qS3vgZZ\/0r6eZmHjrGcPL+zFsTFa12B1adJ6SaXAQxE4HTFOvxpIcfXs6hpVtw==","access_token":"24.f3812c72041050c914f834be440bc993.2592000.1707591733.282335-46678315","scope":"ai_custom_yiyan_com_tokenizer_eb ai_custom_yiyan_com_mixtral_8x7b public brain_all_scope ai_custom_yiyan_com ai_custom_yiyan_com_eb_instant wenxinworkshop_mgr ai_custom_yiyan_com_bloomz7b1 ai_custom_yiyan_com_emb_text ai_custom_yiyan_com_llama2_7b ai_custom_yiyan_com_llama2_13b ai_custom_yiyan_com_llama2_70b ai_custom_yiyan_com_chatglm2_6b_32k ai_custom_yiyan_com_aquilachat_7b ai_custom_yiyan_com_emb_bge_large_zh ai_custom_yiyan_com_emb_bge_large_en ai_custom_yiyan_com_qianfan_chinese_llama_2_7b ai_custom_qianfan_bloomz_7b_compressed ai_custom_yiyan_com_eb_pro ai_custom_yiyan_com_sd_xl ai_custom_yiyan_com_8k ai_custom_yiyan_com_ai_apaas ai_custom_yiyan_com_qf_chinese_llama_2_13b ai_custom_yiyan_com_sqlcoder_7b ai_custom_yiyan_com_codellama_7b_ins ai_custom_yiyan_com_xuanyuan_70b_chat ai_custom_yiyan_com_yi_34b ai_custom_yiyan_com_chatlaw ai_custom_yiyan_com_emb_tao_8k wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\u6743\u9650 vis-classify_flower lpq_\u5f00\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\u5f00\u653eScope vis-ocr_\u865a\u62df\u4eba\u7269\u52a9\u7406 idl-video_\u865a\u62df\u4eba\u7269\u52a9\u7406 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx","session_secret":"9a0598f368930eb308c5e1d3aa157f31"}
    }

}
